<?php

namespace App\System\Goods\Repositories;


use App\Module\Api\Controllers\Request\TableRequest;
use App\System\Base\Helpers\Traits\SinglePattern;
use App\System\Base\Repositories\Repository;
use App\System\Goods\Model\GoodsAlbum;
use App\System\Goods\Model\GoodsInfo;
use Illuminate\Support\Facades\DB;

class GoodsInfoRepository extends Repository
{
    use SinglePattern;

    /**
     * @param string $keyword
     * @param string $status
     * @param string $type
     * @param bool $getall false 分页 true 不分页
     * @return mixed
     */
    public function getList($keyword='',$status='',$type='',$getall=false)
    {
        if($getall){
            $data = GoodsInfo::when($keyword,function ($qurey) use($keyword,$type){
                if($type == 1){
                    return $qurey->where('name','like','%'.$keyword.'%');
                }else if ($type == 2){
                    return $qurey->where('id','like','%'.$keyword.'%');
                }else{
                    return $qurey->where('name','like','%'.$keyword.'%')
                        ->orWhere('id','like','%'.$keyword.'%');
                }
            })
                ->when($status,function ($query) use($status){
                    return $query->where('status',$status);
                })
                ->orderBy('id','desc')
                ->get();
        }else{
            $data = GoodsInfo::when($keyword,function ($qurey) use($keyword,$type){
                if($type == 1){
                    return $qurey->where('name','like','%'.$keyword.'%');
                }else if ($type == 2){
                    return $qurey->where('id','like','%'.$keyword.'%');
                }else{
                    return $qurey->where('name','like','%'.$keyword.'%')
                        ->orWhere('id','like','%'.$keyword.'%');
                }
            })
                ->when($status,function ($query) use($status){
                    return $query->where('status',$status);
                })
                ->orderBy('id','desc')
                ->paginate();
        }
        return $data;
    }

    /**
     * @param $data
     * @param $imgdata
     * @return array|bool
     */
    public function addData($data,$imgdata)
    {
        if(!$data){
            return false;
        }
        DB::beginTransaction();
        $bool1 = GoodsInfo::create($data);
        $bool2 = true;
        if($imgdata){
            foreach ($imgdata as $v){
                $imgUpdata = [];
                $imgUpdata['image_id'] = $v['image_id'];
                $imgUpdata['sort'] = $v['sort'];
                $imgUpdata['goods_id'] = $bool1->id;
                $imgUpdata['created_at'] = date('Y-m-d H:i:s',time());
                $res = GoodsAlbum::insertGetId($imgUpdata);
                if(!$res){
                    $bool2 = false;
                }
            }
        }
        if($bool1 && $bool2){
            $bool = true;
            $msg = '操作成功！';
            DB::commit();
        }else{
            $bool = false;
            $msg = '操作失败！';
            DB::rollBack();
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * @param $id
     * @param $updata
     * @param $imgdata
     * @return array|bool
     */
    public function updateData($id,$updata,$imgdata){
        if(!$id){
            return false;
        }
        DB::beginTransaction();
        $goods = GoodsInfo::find($id);
        if (isset($updata['name'])){
            $goods->name = $updata['name']??'';
            $goods->decription = $updata['decription']??'';
            $goods->cost_price = $updata['cost_price']??'';
            $goods->stock = $updata['stock']??'';
            $goods->key_word = $updata['key_word']??'';
            $goods->content = $updata['content']??'';
        }
        if(isset($updata['status'])){
            $goods->status = $updata['status']??'';
        }
        $bool1 = $goods->save();
        $bool2 = true;
        if($imgdata){
            $newArr = [];
            foreach ($imgdata as $k=>$v){
                $newArr[$v['image_id']] = $v;
            }
            $imgList = GoodsAlbum::where('goods_id',$id)->get(['id','image_id']);
            $oldArr = [];
            if($imgList){
                $imgList = $imgList->toArray();
                foreach ($imgList as $k=>$v){
                    $oldArr[$v['image_id']] = $v;
                }
            }
            $imgUpdate = array_intersect(array_keys($oldArr),array_keys($newArr));
            $imgAdd = array_diff(array_keys($newArr),array_keys($oldArr));
            $imgDel = array_diff(array_keys($oldArr),array_keys($newArr));
            if($imgDel){
                $res1 = GoodsAlbum::where('goods_id',$id)->whereIn('image_id',$imgDel)->delete();
                if(!$res1){
                    $bool2 = false;
                }
            }
            if($imgUpdate){
                foreach ($imgUpdate as $v){
                    $imgUpdata = [];
                    $imgUpdata['sort'] = $newArr[$v]['sort'];
                    $res2 = GoodsAlbum::where('id',$oldArr[$v]['id'])->update($imgUpdata);
                    if(!$res2){
                        $bool2 = false;
                    }
                }
            }
            if($imgAdd){
                foreach ($imgAdd as $v){
                    $imgUpdata = [];
                    $imgUpdata['goods_id'] = $id;
                    $imgUpdata['image_id'] = $v;
                    $imgUpdata['sort'] = $newArr[$v]['sort'];
                    $res3 = GoodsAlbum::insertGetId($imgUpdata);
                    if(!$res3){
                        $bool2 = false;
                    }
                }
            }
        }else{
            $imgIds = GoodsAlbum::where('goods_id',$id)->get(['id']);
            if($imgIds){
                foreach ($imgIds as $v){
                    if(!GoodsAlbum::where('id',$v->id)->delete()){
                        $bool2 = false;
                    }
                }
            }
        }
        if($bool1 && $bool2){
            $bool = true;
            $msg = '操作成功！';
            DB::commit();
        }else{
            $bool = false;
            $msg = '操作失败！';
            DB::rollBack();
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * @param $id
     * @param $updata
     * @return array|bool
     */
    public function update($id,$updata){
        if(!$id){
            return false;
        }
        $goods = GoodsInfo::find($id);
        $goods->status = $updata['status']??'';
        $bool = $goods->save();
        if($bool){
            $msg = '操作成功！';
        }else{
            $msg = '操作失败！';
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * @param $id
     * @return array|bool
     */
    public function deleteData($id)
    {
        if(!$id){
            return false;
        }
        $bool = GoodsInfo::where('id',$id)->first()->delete();
        if($bool){
            $msg = '操作成功！';
        }else{
            $msg = '操作失败！';
        }
        return ['data' => $bool, 'message' => $msg];
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getDetail($id)
    {
        return GoodsInfo::where('id',$id)->first();
    }


    /**
     *API 获取财务记录列表
     * @param $request object
     * @return array
     */
    public function getApiList(TableRequest $request)
    {
        $data = GoodsInfo::where("status",1)
            ->orderBy($request->orderBy,$request->orderType)
            ->paginate($request->limit,['*'],'page',$request->page);
        $goods_ids = [];
        foreach($data as $value)
        {
            $goods_ids[] = $value->id;
        }
        $goods_album_array = [];
        if($goods_ids)
        {
            $goods_album = GoodsAlbumRepository::getInstance();
            $goods_album_array = $goods_album->getInIds($goods_ids);
        }

        foreach($data as $v) {
            $item = [];
            $item['id'] = $v->id;
            $item['name'] = $v->name;
            $item['price'] = $v->member_price;
            $item['originalPrice'] = $v->market_price;
            $item['saleNumber'] = $v->sales_volume;
            $item['imagePath'] = isset($goods_album_array[$v->id]) ? $goods_album_array[$v->id] : '' ;
            $return['goodses'][] = $item;
        }
        $return['total'] =$data->total();
        return $return;
    }
}